package no.kolstad.movies.service;
/**
 *  Copyright [2008] Christopher Kolstad
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
 * Unless required by applicable law or agreed to in writing, software distributed under the License 
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License. 
 */

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import no.kolstad.movies.dao.RoleDAO;
import no.kolstad.movies.dao.UserDAO;
import no.kolstad.movies.model.Role;
import no.kolstad.movies.model.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author chriswk
 */
public class UserService {
    private UserDAO userDao;
    private RoleDAO roleDao;
    private RoleService rService;
    private MovieService mService;
    
    public void setUserDAO(UserDAO dao) {
        this.userDao = dao;
    }
    
    public void setRoleDAO(RoleDAO dao) {
        this.roleDao = dao;
    }
    
    public void setRoleService(RoleService service) {
        this.rService = service;
    }
    
    public void setMovieService(MovieService service) {
        this.mService = service;
    }
    
    protected Log log = LogFactory.getLog(this.getClass());
    
    /**
   * Ensure that a root user and 
   * the four necessary roles exist
   */
  
  public void ensureRoot() {
    
    if(log.isDebugEnabled()) {
      log.debug("Checking roles");
    }
    createRoles();
    checkRootUser();
    ensureRootUsersCollection();
    
    
    
  }
  /**
   * Checks that the Roles needed for User administration
   * and other administrative tasks are in place
   */
  public void createRoles() {
    rService.createRole("User", "ROLE_USER");
    rService.createRole("Administrator", "ROLE_ADMINISTRATOR");
    rService.createRole("Supervisor", "ROLE_SUPERVISOR");
    rService.createRole("ROOT", "ROLE_ROOT");
    rService.createRole("Collector", "ROLE_COLLECTOR");
  }
  
  public void checkRootUser() {
    if(userDao.get("root") == null) {
      if(log.isDebugEnabled()) {
        log.debug("Root user did not exist. Creating it.");
      }
      createRootUser();
    }
    else {
      if(log.isDebugEnabled()) {
        log.debug("Root user existed");
      }
    }
  }

  public List<User> loadUsers() {
      Role rootRole = roleDao.getRole("ROLE_ROOT");
      List<User> users = userDao.loadAll();
      Iterator<User> iter = users.iterator();
      List<User> noRootUser = new ArrayList<User>();
      while(iter.hasNext()) {
          User u2 = iter.next();
          if(!u2.getRoles().contains(rootRole) && !u2.getUsername().equals("root")) {
              if(log.isDebugEnabled()) {
                  log.debug("User had roles: " +u2.getRoles());
              }
              noRootUser.add(u2);
          }
      }
      return noRootUser;
  }
  public void delete(Long id) {
      delete(userDao.get(id));
  }
  public void delete(User u) {
      mService.deleteMoviesForUser(u);
      userDao.remove(u);
      
  }
  private void createRootUser() {
    User root = new User();
    root.setUsername("root");
    root.setPassword("yoSemite");
    root.setActiveflag(true);
    Set<Role> roles = new HashSet<Role>();
    roles.add(roleDao.getRole("ROLE_USER"));
    roles.add(roleDao.getRole("ROLE_ADMINISTRATOR"));
    roles.add(roleDao.getRole("ROLE_SUPERVISOR"));
    roles.add(roleDao.getRole("ROLE_ROOT"));
    roles.add(roleDao.getRole("ROLE_COLLECTOR"));
    root.setRoles(roles);
    if(log.isDebugEnabled()) {
      log.debug("Saving root user: " +root);
    }
    userDao.save(root);
  }
   
  private void ensureRootUsersCollection() {
    User root = userDao.get("root");
  }
  
}
